﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MVCms.Core.Developers;
using MVCms.Core.Entities;
using MVCms.Core.Services;


namespace Plugin.MainNavigation.Controllers
{
    public class MainNavigationController : BaseController
    {
        private StringBuilder _menu;

        [PluginModule(Name = "MainNavigation", Description = "The Core Navigation system of MVCms", DisplayName = "Main Navigation")]
        public PartialViewResult MainNavigation()
        {
            IList<VirtualPage> virtualPages = PageService.GetPages();
            IList<VirtualPage> rootPages = virtualPages.Where(p => p.Parent == null).ToList();
           
            _menu = new StringBuilder();

            _menu.AppendLine("<ul>");
            if (rootPages.Count == 0)
            {
                _menu.AppendLine("<li><a href=#>Setup</a></li>");
            }

            foreach (VirtualPage page in rootPages)
            {
                _menu.AppendLine("<li><a href=" + page.Url + ">" + page.Name);
                BuildMenuStructure(page);
                _menu.Append("</a></li>");
            }
            _menu.AppendLine("</ul>");


            return PartialView(new MainNavigationModel { Menu = _menu.ToString() });
        }



        private void BuildMenuStructure(VirtualPage page)
        {
            if (PageService.HasChildren(page))
            {
                _menu.AppendLine("<ul>");
                foreach (VirtualPage child in PageService.Children(page))
                {
                    _menu.AppendLine("<li><a href=" + child.Url + ">" + child.Name);
                    if (PageService.HasChildren(child))
                    {
                        BuildMenuStructure(child);
                    }
                    _menu.Append("</a></li>");
                }
                _menu.AppendLine("</ul>");
            }
        }

        public class MainNavigationModel
        {
            public string Menu { get; set; }
        }
    }
}
